import axios, { AxiosError, AxiosInstance } from 'axios';
import { Notify } from 'quasar';
import { useUserStore } from '@/store/modules/user.ts';

const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
});
// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    // 如果有token，请求头带token
    if (userStore.token) config.headers.token = userStore.token;
    return config;
  },
  error => Promise.reject(error)
);
// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data;
  },
  (error: AxiosError) => {
    let msg = '';
    const status = error.response?.status;
    switch (status) {
      case 401:
        msg = 'token过期';
        break;
      case 403:
        msg = '无权限';
        break;
      case 404:
        msg = '接口不存在';
        break;
      case 500:
        msg = '服务器错误';
        break;
      default:
        msg = '网络错误';
        break;
    }
    Notify.create({
      type: 'negative',
      message: msg,
      position: 'top'
    });
    return Promise.reject(error);
  }
);

export default request;
